<template>
	<div class="indexBox">
		<div class="poundBox">
			<el-card class="poundCard">
				<el-row :gutter="20">
					<!-- 左侧磅房 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="pound-col left-pound"
						style="border-right: 1px dashed #CCC;padding: 10px; box-sizing: border-box;">
						<pound :weightOBJ="counterStore.eastPound"></pound>

						<div class="leftBox">
							<div class="leftBox_name">一磅计量单</div>
							<el-form :model="formAData" :rules="rules" ref="formARef" label-width="100px">
								<el-form-item label="过磅类型" prop="weighingType">
									<el-select style="width: 400px;" v-model="formAData.weighingType"
										placeholder="请选择过磅类型"
										@change="(val) => handleWeighingTypeChange('1001', Number(val))">
										<el-option v-for="item in options" :key="item.value" :label="item.label"
											:value="item.value" />
									</el-select>
								</el-form-item>

								<el-form-item label="车牌号码" prop="autoLicense">
									<el-input v-model="formAData.autoLicense" style="width: 400px;"
										placeholder="例：京A12345" @input="handleInput('1001',$event)" />
								</el-form-item>
								<el-form-item label="集装箱号码" >
									<el-input v-model="formAData.containerNum" style="width: 400px;"
										placeholder="请填写集装箱号码"  />
								</el-form-item>
								<el-form-item label="货物名称" prop="cargoName">
									<el-select v-model="formAData.cargoName" filterable allow-create
										default-first-option :reserve-keyword="false" placeholder="请输入或选择货物名称"
										style="width: 400px" @change="(val) => handleCargoChange(val, formAData)"
										value-key="id" clearable>
										<el-option v-for="item in cargoOptions" :key="item.cargoName"
											:label="item.cargoName" :value="item.cargoName">
											<span>{{ item.cargoName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="发货厂家" prop="shippingCompanyId">
									<el-select v-model="formAData.shippingCompanyId" filterable default-first-option
										:reserve-keyword="false" placeholder="请选择发货厂家" style="width: 400px"
										value-key="id" clearable
										@change="(val) => handleCompanyChange('shipping', val, formAData, '1001')">
										<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="收货厂家" prop="receivingCompanyId">
									<el-select v-model="formAData.receivingCompanyId" filterable default-first-option
										:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 400px"
										value-key="id" clearable
										@change="(val) => handleCompanyChange('receiving', val, formAData, '1001')">
										<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="规格" prop="specifications">
									<el-input v-model="formAData.specifications" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="司机姓名" prop="driverName">
									<el-input v-model="formAData.driverName" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="一次过磅(t)" prop="aWeight">
									<el-input-number v-model="formAData.aWeight" :min="0" :precision="2"
										style="width: 400px;" disabled class="custom-input-number" />
								</el-form-item>
								<el-form-item label="二次过磅(t)" prop="secondWeight">
									<el-input-number v-model="formAData.secondWeight" :min="0" :precision="2"
										style="width: 400px;" disabled class="custom-input-number" />
								</el-form-item>
								<el-form-item v-if="formAData.weightStatus===1 && formAData.secondWeight>0"
									label="净重(t)" prop="suttle">
									<el-input-number :min="0" v-model="formAData.suttle" disabled style="width: 400px;"
										class="custom-input-number" :precision="3" />
								</el-form-item>
								<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
									<el-button type="primary"
										@click="handleFormAction(formARef, formAData, 'SUBMIT', '1001')">提交</el-button>
								</div>
							</el-form>
						</div>
					</el-col>

					<!-- 右侧磅房 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="pound-col right-pound"
						style="padding: 10px;box-sizing: border-box;">
						<pound :weightOBJ="counterStore.westPound"></pound>
						<div class="rightBox">
							<div class="rightBox_name">二磅计量单</div>
							<el-form :model="formBData" :rules="rules" ref="formBRef" label-width="100px">
								<el-form-item label="过磅类型" prop="weighingType">
									<el-select style="width: 400px;" v-model="formBData.weighingType"
										placeholder="请选择过磅类型"
										@change="(val) => handleWeighingTypeChange('1002', Number(val))">
										<el-option v-for="item in options" :key="item.value" :label="item.label"
											:value="item.value" />
									</el-select>
								</el-form-item>
								<el-form-item label="车牌号码" prop="autoLicense">
									<el-input v-model="formBData.autoLicense" placeholder="例：京A12345"
										style="width: 400px;" @input="handleInput('1002',$event)" />
								</el-form-item>
								<el-form-item label="集装箱号码" >
									<el-input v-model="formBData.containerNum" style="width: 400px;"
										placeholder="请填写集装箱号码"  />
								</el-form-item>

								<el-form-item label="货物名称" prop="cargoName">
									<el-select v-model="formBData.cargoName" filterable default-first-option
										:reserve-keyword="false" placeholder="请输入或选择货物名称" style="width: 400px"
										@change="(val) => handleCargoChange(val, formBData)" value-key="id" clearable>
										<el-option v-for="item in cargoOptions" :key="item.cargoName"
											:label="item.cargoName" :value="item.cargoName">
											<span>{{ item.cargoName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="发货厂家" prop="shippingCompanyId">
									<el-select v-model="formBData.shippingCompanyId" filterable :reserve-keyword="false"
										placeholder="请选择发货厂家" style="width: 400px" value-key="id" clearable
										@change="(val) => handleCompanyChange('shipping', val, formBData, '1002')">
										<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="收货厂家" prop="receivingCompanyId">
									<el-select v-model="formBData.receivingCompanyId" filterable
										:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 400px"
										value-key="id" clearable
										@change="(val) => handleCompanyChange('receiving', val, formBData, '1002')">
										<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName"
											:value="item.id">
											<span>{{ item.companyName }}</span>
										</el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="规格" prop="specifications">
									<el-input v-model="formBData.specifications" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="司机姓名" prop="driverName">
									<el-input v-model="formBData.driverName" style="width: 400px;" />
								</el-form-item>
								<el-form-item label="一次过磅(t)" prop="aWeight">
									<el-input-number v-model="formBData.aWeight" :min="0" :precision="2"
										style="width: 400px;" disabled class="custom-input-number" />
								</el-form-item>
								<el-form-item label="二次过磅(t)" prop="secondWeight">
									<el-input-number v-model="formBData.secondWeight" :min="0" :precision="2"
										style="width: 400px;" disabled class="custom-input-number" />
								</el-form-item>
								<el-form-item v-if="formBData.weightStatus===1 && formBData.secondWeight>0"
									label="净重(t)" prop="suttle">
									<el-input-number :min="0" v-model="formBData.suttle" disabled style="width: 400px;"
										class="custom-input-number" :precision="3" />
								</el-form-item>
								<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
									<el-button type="primary"
										@click="handleFormAction(formBRef, formBData, 'SUBMIT','1002')">提交</el-button>
								</div>
							</el-form>
						</div>
					</el-col>
				</el-row>
			</el-card>
		</div>
	</div>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
		nextTick,
		watch,
		onBeforeUnmount,
		getCurrentInstance,
		onActivated,
		toRaw
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	const {
		proxy
	} = getCurrentInstance()
	import { useRouter } from 'vue-router'
	import type { FormInstance, FormRules } from 'element-plus'
	import pound from '@/components/pound/pound.vue'
	import poundDialog from '@/components/poundDialog/poundDialog.vue'
	import { debounce } from 'lodash-es'
	import { useCounterStore } from '@/stores/index'
	import { useLogout } from '@/utils/logout'

	const { logout } = useLogout()
	const counterStore = useCounterStore()
	interface CargoOption {
		cargoName : string
		id : string
		specifications ?: string
	}
	interface CompanyOption {
		companyName : string
		id : string
		suttle : number
		tare : number;
		roughWeight : number

	}
	const cargoOptions = ref<CargoOption[]>([])
	const caiOptions = ref<CompanyOption[]>([])
	const xiaoOptions = ref<CompanyOption[]>([])
	const options = [
		{ label: '采购', value: 1 },
		{ label: '销售', value: 2 }
	]

	// 添加临时禁用实时更新的标记
	const disableRealtimeUpdate = ref({
		'1001': {
			status: false,
			reason: '' // 记录禁用原因：'history-loading' | 'manual-edit' | ''
		},
		'1002': {
			status: false,
			reason: ''
		}
	})

	// 统一缓存配置
	const CACHE_CONFIG = {
		getKey(loadCode : string) {
			return `weighing_form_${loadCode}`; // 缓存键前缀，避免冲突
		},
		expireTime: 1 * 60 * 60 * 1000, // 缓存有效期：24小时
	};

	// 缓存读取工具函数
	const getCacheData = (loadCode : string) => {
		const cacheKey = CACHE_CONFIG.getKey(loadCode);

		const cacheStr = localStorage.getItem(cacheKey);
		if (!cacheStr) return null;

		try {
			const cache = JSON.parse(cacheStr);
			// 判断缓存是否过期
			const isExpired = Date.now() - cache.timestamp > CACHE_CONFIG.expireTime;
			if (isExpired) {
				localStorage.removeItem(cacheKey);
				return null;
			}

			// 判断缓存数据是否有效
			const cacheData = cache.data;
			if (!cacheData || (!cacheData.autoLicense && cacheData.aWeight <= 0 && cacheData.secondWeight <= 0)) {
				localStorage.removeItem(cacheKey);
				return null;
			}

			return cacheData;
		} catch (error) {
			console.error(`读取${loadCode}磅缓存失败：`, error);
			localStorage.removeItem(cacheKey);
			return null;
		}
	};

	// 缓存保存工具函数 - 用户离开页面后回来读取缓存数据
	const saveFormCache = (loadCode : string, formData : WeighingFormData) => {
		try {
			const cacheKey = CACHE_CONFIG.getKey(loadCode);

			const cacheData = {
				data: { ...formData },
				timestamp: Date.now()
			};
			localStorage.setItem(cacheKey, JSON.stringify(cacheData));
		
		} catch (error) {
			console.error(`保存${loadCode}磅缓存失败：`, error);
		}
	};

	// 先定义表单数据结构（关键：确保在watch之前定义）
	type WeighingStatus = 0 | 1 | 2

	interface WeighingFormData {
		id : number | null;
		autoLicense : string;
		containerNum:string;
		cargoName : string;
		driverName : string;
		shippingCompanyId : string;
		receivingCompanyId : string;
		specifications : string;
		aWeight : number;
		secondWeight : number;
		suttle : number;
		weightStatus : number;
		deductingId : string;
		weighingType : number;
		// 用于存储历史数据，不会被实时数据覆盖
		historicalAWeight : number;
		historicalSecondWeight : number;
		// 标记是否已根据过磅类型调整过重量
		weightsAdjusted : boolean;
		// 记录实时数据应该推送到哪个字段
		realtimeTarget : 'aWeight' | 'secondWeight' | 'none';
		hasLoadedHistory : boolean;      // 新增：标记是否已加载历史数据
		isManualAdjust : boolean; // 标记是否手动调整过重量
		isLoadingHistory : boolean; // 标记是否正在加载历史数据
		// 前端自用字段，不发送给后端
		hasSubmittedFirstWeigh : boolean; // 标记是否已提交过一次过磅
		frontendWeighStatus : number; // 前端维护的称重状态，用于界面逻辑
		lastSecondWeight : number;
		secondWeightTimer : NodeJS.Timeout | number | null;
		originalAWeight ?: number;
		originalSecondWeight ?: number;
	}

	// 地磅A配置（关键：提前定义，确保watch时已初始化）
	const formARef = ref<FormInstance>()
	const formAData = reactive<WeighingFormData>({
		id: null,
		autoLicense: '',
		containerNum:'',
		cargoName: '',
		driverName: '',
		shippingCompanyId: '',
		receivingCompanyId: '',
		specifications: '',
		aWeight: 0,
		secondWeight: 0,
		suttle: 0,
		weightStatus: 0,
		deductingId: '',
		weighingType: 1,
		historicalAWeight: 0,
		historicalSecondWeight: 0,
		weightsAdjusted: false,
		realtimeTarget: 'aWeight',
		hasLoadedHistory: false, // 新增：初始未加载历史数据
		isManualAdjust: false,
		isLoadingHistory: false,
		hasSubmittedFirstWeigh: false, // 前端字段：标记是否已提交一次过磅
		frontendWeighStatus: 0, // 前端字段：维护的称重状态
		lastSecondWeight: 0,        // 上次二次重量（用于稳定判断）
		secondWeightTimer: null,    // 二次重量定时器（用于延迟计算）
		originalAWeight: undefined,  // 一次过磅原始值（避免归零）
		originalSecondWeight: undefined  // 二次过磅原始值（避免归零）
	})

	// 地磅B配置（关键：提前定义，确保watch时已初始化）
	const formBRef = ref<FormInstance>()
	const formBData = reactive<WeighingFormData>({
		id: null,
		autoLicense: '',
		containerNum:'',
		cargoName: '',
		driverName: '',
		shippingCompanyId: '',
		receivingCompanyId: '',
		specifications: '',
		aWeight: 0,
		secondWeight: 0,
		suttle: 0,
		weightStatus: 0,
		deductingId: '',
		weighingType: 1,
		historicalAWeight: 0,
		historicalSecondWeight: 0,
		weightsAdjusted: false,
		realtimeTarget: 'aWeight',
		hasLoadedHistory: false, // 新增：初始未加载历史数据
		isManualAdjust: false,
		isLoadingHistory: false,
		hasSubmittedFirstWeigh: false, // 前端字段：标记是否已提交一次过磅
		frontendWeighStatus: 0, // 前端字段：维护的称重状态
		lastSecondWeight: 0,        // 上次二次重量（用于稳定判断）
		secondWeightTimer: null,    // 二次重量定时器（用于延迟计算）
		originalAWeight: undefined,  // 一次过磅原始值（避免归零）
		originalSecondWeight: undefined  // 二次过磅原始值（避免归零）
	})

	// 表单规则（放在表单数据后面定义）
	const rules = reactive<FormRules<WeighingFormData>>({
		autoLicense: [
			{ required: true, message: '请输入车牌号', trigger: 'blur' },
			{
				pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
				message: '请输入有效车牌号', trigger: 'blur'
			}
		],
		cargoName: [
			{ required: true, message: '请输入货物名称', trigger: 'blur' }
		],
		shippingCompanyId: [
			{ required: true, message: '请选择发货厂家', trigger: 'blur' },
		],
		receivingCompanyId: [
			{ required: true, message: '请选择收货厂家', trigger: 'blur' },
		],
		aWeight: [
			{ type: 'number', min: 0, message: '重量必须大于0', trigger: 'blur' }
		],
		secondWeight: [
			{ type: 'number', min: 0, message: '重量必须大于0', trigger: 'blur' }
		]
	})

	// 货物选择变化处理
	const handleCargoChange = (val : string, formData : Record<string, any>) => {
		// 查找匹配的货物项
		const matchingCargo = cargoOptions.value.find(
			(cargo) => formData.cargoName === cargo.cargoName
		);

		if (matchingCargo) {
			// 将匹配项的规格赋值给formData
			formData.specifications = matchingCargo.specifications;
		}

		// 检查货物是否已存在，不存在则添加
		if (!cargoOptions.value.some(item => item.cargoName === val)) {
			cargoOptions.value.push({
				cargoName: val,
				id: val,
			});
		}
	};

	const router = useRouter()

	const dongnum = ref(null)
	const xinum = ref(null)

	// ========== 扣重计算相关 ==========
	// 重量稳定性判断相关
	const weightStability = ref({
		'1001': {
			lastWeight: 0,
			stableCount: 0,
			isStable: false,
			timer: null as NodeJS.Timeout | null
		},
		'1002': {
			lastWeight: 0,
			stableCount: 0,
			isStable: false,
			timer: null as NodeJS.Timeout | null
		}
	})

	// 检查重量是否稳定
	const checkWeightStability = (loadCode : string, currentWeight : number) : boolean => {
		const stability = weightStability.value[loadCode];
		const minStableCount = 3; // 连续3次稳定才判定为稳定
		const weightThreshold = 0.02; // 重量波动阈值（吨，如±0.02吨视为稳定）

		// 关键：如果当前重量比上一次大很多（还在上升），直接重置稳定计数
		if (currentWeight - stability.lastWeight > weightThreshold * 2) {
			stability.stableCount = 0; // 上升阶段，不稳定
			stability.isStable = false;
			stability.lastWeight = currentWeight;
			
			return false;
		}

		// 正常波动判断：变化小于阈值视为稳定
		const isStableOnce = Math.abs(currentWeight - stability.lastWeight) < weightThreshold;

		if (isStableOnce) {
			stability.stableCount++; // 连续稳定次数+1
			stability.isStable = stability.stableCount >= minStableCount;
		} else {
			stability.stableCount = 0; // 波动超过阈值，重置
			stability.isStable = false;
		}

		stability.lastWeight = currentWeight;
		return stability.isStable;
	};
	
	
	
	// 验证重量合理性
	// const validateWeightLogic = (
	// 	formData : WeighingFormData,
	// 	loadCode : string
	// ) : { valid : boolean; message ?: string; suggestion ?: string } => {
	// 	const { aWeight, secondWeight, weighingType } = formData

	// 	// 采购模式：一次（毛重）应该大于二次（皮重）
	// 	if (weighingType === 1) {
	// 		if (aWeight < secondWeight) {
	// 			return {
	// 				valid: false,
	// 				message: '采购模式下，一次过磅（毛重）应大于二次过磅（皮重）',
	// 				suggestion: '建议切换到销售模式或检查重量数据'
	// 			}
	// 		}
	// 	}

	// 	// 销售模式：一次（皮重）应该小于二次（毛重）
	// 	if (weighingType === 2) {
	// 		if (aWeight > secondWeight) {
	// 			return {
	// 				valid: false,
	// 				message: '销售模式下，一次过磅（皮重）应小于二次过磅（毛重）',
	// 				suggestion: '建议切换到采购模式或检查重量数据'
	// 			}
	// 		}
	// 	}

	// 	return { valid: true }
	// }
	
	
	const validateWeightLogic = (() => {
	  // 闭包存储冷却状态：key=磅房编号_错误类型标识，value=上次允许弹框时间戳
	  const errorCoolDownMap = new Map<string, number>();
	  const COOL_DOWN_TIME = 3000; // 3秒冷却
	  const WEIGHT_TOLERANCE = 0.02; // 磅秤容差（0.02吨，可根据实际精度调整）
	
	  return (
	    formData: WeighingFormData,
	    loadCode: string
	  ): {
	    valid: boolean;
	    message?: string;
	    suggestion?: string;
	    allowAlert: boolean; // 新增：是否允许弹框（冷却控制）
	  } => {
	    const { aWeight, secondWeight, weighingType } = formData;
	    let valid = true;
	    let message: string | undefined;
	    let suggestion: string | undefined;
	
	    // 核心1：微小容差过滤（避免磅秤抖动导致的误判）
	    if (weighingType === 1) {
	      // 采购模式：毛重（aWeight）≥ 皮重（secondWeight）- 容差
	      if (aWeight < secondWeight - WEIGHT_TOLERANCE) {
	        valid = false;
	        message = '采购模式下，一次过磅（毛重）应大于二次过磅（皮重）';
	        suggestion = '建议切换到销售模式或检查重量数据';
	      }
	    } else if (weighingType === 2) {
	      // 销售模式：皮重（aWeight）≤ 毛重（secondWeight）- 容差
	      if (aWeight > secondWeight - WEIGHT_TOLERANCE) {
	        valid = false;
	        message = '销售模式下，一次过磅（皮重）应小于二次过磅（毛重）';
	        suggestion = '建议切换到采购模式或检查重量数据';
	      }
	    }
	
	    // 核心2：冷却逻辑（仅校验失败时执行）
	    let allowAlert = false;
	    if (!valid && message) {
	      // 唯一标识：磅房编号_过磅类型_错误信息（确保独立冷却）
	      const errorKey = `${loadCode}_${weighingType}_${message}`;
	      const now = Date.now();
	      const lastAlertTime = errorCoolDownMap.get(errorKey) || 0;
	
	      // 不在冷却期 → 允许弹框，并更新时间戳
	      if (now - lastAlertTime >= COOL_DOWN_TIME) {
	        allowAlert = true;
	        errorCoolDownMap.set(errorKey, now);
	      }
	    }
	
	    return { valid, message, suggestion, allowAlert };
	  };
	})();

	// 核心扣重计算函数
	const calculateWeightWithRules = (
		formData : WeighingFormData,
		loadCode : string
	) : { success : boolean; message ?: string } => {
		try {
			// 1. 基础条件检查 - 支持状态1（一次过磅后自动计算）和状态2（手动厂家变更时重新计算）
			if (formData.weightStatus !== 1 && formData.weightStatus !== 2) {
				return { success: false, message: '需要至少完成一次过磅' }
			}

			if (!formData.secondWeight || formData.secondWeight <= 0) {
				return { success: false, message: '二次重量未就绪' }
			}

			if (!formData.aWeight || formData.aWeight <= 0) {
				return { success: false, message: '一次重量无效' }
			}

			// 1.5 验证重量逻辑合理性
			const weightValidation = validateWeightLogic(formData, loadCode);
			if (!weightValidation.valid) {
			  // 如需启用弹框，增加 allowAlert 判断
			  if (weightValidation.allowAlert) {
			    ElMessage({
			      type: 'warning',
			      message: weightValidation.message,
			      duration: 3000
			    });
			    if (weightValidation.suggestion) {
			      setTimeout(() => {
			        ElMessage({
			          type: 'info',
			          message: weightValidation.suggestion,
			          duration: 2500
			        });
			      }, 500);
			    }
			  }
			  return { success: false, message: weightValidation.message };
			}

			// 2. 根据过磅类型获取对应厂家的扣重规则
			let companyRules = {
				tare: 0,        // 皮重调整值
				roughWeight: 0, // 毛重调整值
				suttle: 1       // 净重系数
			}
				

			if (formData.weighingType === 1) {
				// 采购类型：使用发货厂家的扣重规则
				if (formData.shippingCompanyId) {
					const shippingCompany = caiOptions.value.find(item => item.id === formData.shippingCompanyId)
					if (shippingCompany) {
						companyRules.tare = shippingCompany.tare || 0
						companyRules.roughWeight = shippingCompany.roughWeight || 0
						companyRules.suttle = shippingCompany.suttle || 1
						
					}
				}
			} else if (formData.weighingType === 2) {
				// 销售类型：使用收货厂家的扣重规则
				if (formData.receivingCompanyId) {
					const receivingCompany = xiaoOptions.value.find(item => item.id === formData.receivingCompanyId)
					if (receivingCompany) {
						companyRules.tare = receivingCompany.tare || 0
						companyRules.roughWeight = receivingCompany.roughWeight || 0
						companyRules.suttle = receivingCompany.suttle || 1
						
					}
				}
			}

			// 3. 根据过磅类型计算修正后的重量
			let correctedTare = 0  // 皮重（吨）
			let correctedRoughWeight = 0  // 毛重（吨）
			// 使用原始重量进行计算，避免污染显示数据
			let originalAWeight = formData.originalAWeight || formData.aWeight  // 原始一次重量（吨）
			let originalSecondWeight = formData.originalSecondWeight || formData.secondWeight  // 原始二次重量（吨）

			if (formData.weighingType === 1) {
				// 采购：一次过磅=毛重，二次过磅=皮重
				correctedRoughWeight = parseFloat((originalAWeight + companyRules.roughWeight).toFixed(3))
				correctedTare = parseFloat((originalSecondWeight + companyRules.tare).toFixed(3))
				
			} else if (formData.weighingType === 2) {
				// 销售：一次过磅=皮重，二次过磅=毛重
				correctedTare = parseFloat((originalAWeight + companyRules.tare).toFixed(3))
				correctedRoughWeight = parseFloat((originalSecondWeight + companyRules.roughWeight).toFixed(3))
				
			}



			// 根据过磅类型将扣重后的毛重皮重赋值给显示字段
			if (formData.weighingType === 1) {
				// 采购：一次重量为毛重，二次重量为皮重
				if (correctedRoughWeight > correctedTare) {
					formData.aWeight = correctedRoughWeight      // 扣重后毛重赋值给一次过磅
					formData.secondWeight = correctedTare        // 扣重后皮重赋值给二次过磅
				} else {
					formData.aWeight = correctedTare
					formData.secondWeight = correctedRoughWeight        // 扣重后皮重赋值给二次过磅
				}


				// formData.realtimeTarget = 'none';
			} else if (formData.weighingType === 2) {
				// 销售：一次重量为皮重，二次重量为毛重 
				if (correctedTare > correctedRoughWeight) {
					formData.aWeight = correctedRoughWeight             // 扣重后皮重赋值给一次过磅
					formData.secondWeight = correctedTare // 扣重后毛重赋值给二次过磅
				} else {
					formData.aWeight = correctedTare             // 扣重后皮重赋值给一次过磅
					formData.secondWeight = correctedRoughWeight // 扣重后毛重赋值给二次过磅
				}

				// formData.realtimeTarget = 'none';

			}

			// 4. 计算净重（单位：吨）
			// 净重 = (毛重 - 皮重) × 净重系数
			const netWeight = parseFloat(((correctedRoughWeight - correctedTare) * companyRules.suttle).toFixed(3))


			// 5. 更新表单数据（保存原始重量，显示扣重后重量）
			// 保存原始重量（如果还没保存的话）
			if (formData.originalAWeight === undefined) {
				formData.originalAWeight = formData.aWeight
			}
			if (formData.originalSecondWeight === undefined) {
				formData.originalSecondWeight = formData.secondWeight
			}

			// 更新净重
			formData.suttle = Math.abs(netWeight)
			

			

			// 保存缓存
			saveFormCache(loadCode, formData)

			return { success: true }
		} catch (error) {
			
			return { success: false, message: '扣重计算异常' }
		}
	}
	
	const debounceEastCheck = debounce((license: string) => {
		// && license !== formAData.autoLicense
	  if (license ) {
	    formAData.autoLicense = license;
	    checkLicensePlate('1001', license, false);
	  }
	}, 500); // 500ms内仅触发一次
	
	const debounceWestCheck = debounce((license: string) => {
		// && license !== formBData.autoLicense
	  if (license ) {
	    formBData.autoLicense = license;
	    checkLicensePlate('1002', license, false);
	  }
	}, 500);

	// 东磅实时数据监听逻辑 - 按业务需求重新设计
	watch(
		() => counterStore.eastPound,
		(newPoundData, oldPoundData) => {

			// 实时更新禁用时，忽略更新
			if (disableRealtimeUpdate.value['1001'].status) {

				return;
			}

			// 确保有有效重量数据
			if (newPoundData.weight === undefined) {
				return;
			}


			const incomingLicense = newPoundData.autoLicense?.trim(); // 去除空格，避免空白字符误判
			if (incomingLicense) { // 判断车牌号存在（非空、非空白）
				const eastCacheKey = CACHE_CONFIG.getKey('1001'); // 获取东磅缓存键
				if (localStorage.getItem(eastCacheKey)) { // 检查缓存是否存在
					localStorage.removeItem(eastCacheKey); // 清除东磅缓存
				
				}
			}
			// ------------------------------------------------------------------------------------------

			// 处理车牌号获取 - websocket推送或手动输入（原逻辑保留，调整顺序） && incomingLicense !== formAData.autoLicense
			
			if (incomingLicense ) {
				debounceEastCheck(incomingLicense);
				return; // 等待历史数据查询完成
			}


	
			
			
			const isSameAsOriginalSecond = Math.abs(newPoundData.weight - formAData.originalSecondWeight) < 0.0001;
		
			if (formAData.realtimeTarget === 'aWeight') {
					
				formAData.aWeight = newPoundData.weight;
				formAData.originalAWeight = newPoundData.weight; // 同时更新原始重量
			} else if (formAData.realtimeTarget === 'secondWeight') {
			
				if (!isSameAsOriginalSecond) {
					formAData.secondWeight = newPoundData.weight;
					formAData.originalSecondWeight = newPoundData.weight; // 仅赋值时更新原始重量
					// 当二次重量稳定后，自动计算扣重isStable &&
					if (formAData.weightStatus === 1 && formAData.aWeight > 0 && formAData.secondWeight > 0) {
						// 清除之前的定时器
						if (weightStability.value['1001'].timer) {
							clearTimeout(weightStability.value['1001'].timer)
						}
						// 延迟500ms执行扣重计算，确保数据完全稳定
						weightStability.value['1001'].timer = setTimeout(() => {
							const result = calculateWeightWithRules(formAData, '1001')
								
							
						}, 100)
			
					}
				}
			
			
			
			
			
			} else if (formAData.realtimeTarget === 'none') {
				return
			}
			
			
			



			// 保存缓存（保留）
			if (formAData.autoLicense && formAData.autoLicense.trim()) {
				saveFormCache('1001', formAData);
			}
		},
		{ deep: true }
	);

	// 西磅实时数据监听逻辑 - 按业务需求重新设计
	watch(
		() => counterStore.westPound,
		(newPoundData, oldPoundData) => {
			// 实时更新禁用时，忽略更新
			if (disableRealtimeUpdate.value['1002'].status) {

				return;
			}

			// 确保有有效重量数据
			if (newPoundData.weight === undefined) {
				return;
			}


			const incomingLicense = newPoundData.autoLicense?.trim(); // 去除空格，避免空白字符误判
			if (incomingLicense) { // 判断车牌号存在（非空、非空白）
				const westCacheKey = CACHE_CONFIG.getKey('1002'); // 获取西磅缓存键
				if (localStorage.getItem(westCacheKey)) { // 检查缓存是否存在
					localStorage.removeItem(westCacheKey); // 清除西磅缓存

				}
			}
			// ------------------------------------------------------------------------------------------

			// 处理车牌号获取 - websocket推送或手动输入（原逻辑保留，调整顺序） && incomingLicense !== formBData.autoLicense
			if (incomingLicense ) {
				debounceWestCheck(incomingLicense);
				return; // 等待历史数据查询完成
			}

			const isSameAsOriginalSecond = Math.abs(newPoundData.weight - formBData.originalSecondWeight) < 0.0001;
			
			if (formBData.realtimeTarget === 'aWeight') {
		
				formBData.aWeight = newPoundData.weight;
				formBData.originalAWeight = newPoundData.weight; // 同时更新原始重量
			} else if (formBData.realtimeTarget === 'secondWeight') {

				if (!isSameAsOriginalSecond) {
					formBData.secondWeight = newPoundData.weight;
					formBData.originalSecondWeight = newPoundData.weight; // 仅赋值时更新原始重量
					// 当二次重量稳定后，自动计算扣重isStable &&
					if (formBData.weightStatus === 1 && formBData.aWeight > 0 && formBData.secondWeight > 0) {
						// 清除之前的定时器
						if (weightStability.value['1002'].timer) {
							clearTimeout(weightStability.value['1002'].timer)
						}
						// 延迟500ms执行扣重计算，确保数据完全稳定
						weightStability.value['1002'].timer = setTimeout(() => {
							const result = calculateWeightWithRules(formBData, '1002')
								
							if (result.success) {
								console.log('[西磅] 二次重量稳定，扣重计算成功')
							} else {
								console.log('[西磅] 扣重计算条件不满足:', result.message)
							}
						}, 100)

					}
				}





			} else if (formBData.realtimeTarget === 'none') {
				return
			}
			// 取消“根据过磅类型自动交换重量”的所有代码

			// 保存缓存（保留）
			if (formBData.autoLicense && formBData.autoLicense.trim()) {
				saveFormCache('1002', formBData);
			}
		},
		{ deep: true }
	);


	// 1. 定义请求池：用于跟踪正在进行的请求，key为唯一标识，value为请求的Promise
	const pendingHistoryRequests = new Map<string, Promise<any>>();

	// 2. 检查车牌历史数据的函数（带请求池防重+错误提示优化）
	const checkLicensePlate = async (loadCode : string, cardCode : string, isManualInput : boolean = false) => {
		let targetForm : WeighingFormData = loadCode === '1001' ? formAData : formBData;

		try {
			const upperCardCode = cardCode.toUpperCase().trim();
			// 基本校验：车牌号长度不足3位不查询（优化提示）
			if (upperCardCode.length < 3) {
				
				// 仅手动输入时提示，避免自动推送频繁提示
				if (isManualInput) {
					ElMessage({
						type: 'info',
						message: `请输入完整车牌号（至少3位）`,
						duration: 1500 // 缩短提示时长，减少干扰
					});
				}
				return;
			}

			// 生成唯一请求标识：结合磅房编号和车牌号，避免不同磅房/车牌的请求冲突
			const requestKey = `${loadCode}_${upperCardCode}`;

			// 核心防重逻辑1：如果请求已在池中，直接返回现有Promise（避免重复请求）
			if (pendingHistoryRequests.has(requestKey)) {
				const existingPromise = pendingHistoryRequests.get(requestKey);
				// 新增：若现有请求已失败，删除并重新发起
				if (existingPromise?.isRejected) {
					pendingHistoryRequests.delete(requestKey);
					
				} else {
				
					return existingPromise;
				}
			}

			// 核心防重逻辑2：状态防重（双重保险）
			if (targetForm.isLoadingHistory) {
			
				// 重复触发时轻提示，避免用户困惑
				ElMessage({
					type: 'info',
					message: `正在查询${loadCode === '1001' ? '一磅' : '二磅'}历史数据，请稍候`,
					duration: 1200
				});
				return;
			}

			// 创建请求Promise并加入请求池
			const requestPromise = (async () => {
				// 禁用实时更新，防止请求过程中数据被覆盖
				disableRealtimeUpdate.value[loadCode] = { status: true, reason: 'history-loading' };
				targetForm.isLoadingHistory = true;
			

				try {
					// 发起实际请求
					const res = await proxy.$request.weighFeedback({ autoLicense: upperCardCode });

					// 接口返回统一处理（优化错误提示分级）
					if (!res || !res.data) {
						throw new Error('接口返回格式异常');
					}

					if (res.data.code === 200) {
						// 成功提示仅在有数据时显示，避免无数据时冗余提示
						if (res.data.result) {
							ElMessage({
								type: 'success',
								message: `${loadCode === '1001' ? '一磅' : '二磅'}历史数据查询成功`,
								duration: 1500
							});
						} else {
							ElMessage({
								type: 'info',
								message: `暂无${upperCardCode}的过磅记录，可新建称重`,
								duration: 1800
							});
						}

						if (res.data.result) {
							const historyData : WeighingHistory = res.data.result;
							

							// 保存历史原始重量
							targetForm.historicalAWeight = historyData.aWeight || 0;
							targetForm.historicalSecondWeight = historyData.secondWeight || 0;

							// 复制非重量字段（排除不需要的字段）
							Object.keys(historyData).forEach(key => {
								if (!['aWeight', 'secondWeight', 'suttle', 'weightStatus', 'realtimeTarget', 'isManualAdjust'].includes(key)) {
									// 手动输入时不覆盖用户输入的车牌
									if (key === 'autoLicense' && isManualInput) return;
									targetForm[key] = historyData[key] || '';
								}
							});
							

							// 根据历史数据状态处理重量
							if (historyData.weightStatus === 0 || (historyData.aWeight || 0) === 0) {
								// 无有效历史数据，按新车辆处理
								targetForm.aWeight = 0;
								targetForm.secondWeight = 0;
								targetForm.suttle = 0;
								targetForm.frontendWeighStatus = 0;
								targetForm.realtimeTarget = 'aWeight';
								targetForm.hasLoadedHistory = false;
								targetForm.historicalAWeight = 0;
								targetForm.weightStatus = historyData.weightStatus;
							
							} else if (historyData.weightStatus === 1) {
								// 一次过磅完成状态
								targetForm.aWeight = historyData.aWeight || 0;
								targetForm.secondWeight = historyData.secondWeight || 0;
								// 保存原始重量
								targetForm.originalAWeight = historyData.aWeight || 0;
								targetForm.originalSecondWeight = historyData.secondWeight || 0;
								targetForm.weightStatus = historyData.weightStatus;
								targetForm.frontendWeighStatus = historyData.weightStatus;
								targetForm.realtimeTarget = 'secondWeight';
								targetForm.hasLoadedHistory = true;
								targetForm.historicalAWeight = historyData.aWeight || 0;
								
								
							
								
								
								// 如果已经有二次重量且大于0，立即计算扣重
								// if ((historyData.secondWeight || 0) > 0) {
									

								// 	setTimeout(() => {
								// 		const weightValidation = validateWeightLogic(targetForm, loadCode)
									
								// 		if (weightValidation.valid) {
								// 			const result = calculateWeightWithRules(targetForm, loadCode)
								// 			if (result.success) {
												
								// 			}
								// 		} else {
										
								// 			ElMessage({
								// 				type: 'warning',
								// 				message: `历史数据${weightValidation.message}`,
								// 				duration: 3000
								// 			})
								// 		}
								// 	}, 100)
								// }
								
								
								if ((historyData.secondWeight || 0) > 0) {
								  setTimeout(() => {
								    const weightValidation = validateWeightLogic(targetForm, loadCode);
								    if (weightValidation.valid) {
								      const result = calculateWeightWithRules(targetForm, loadCode);
								      if (result.success) {}
								    } else {
								      // 新增：仅 allowAlert 为 true 时才弹框
								      if (weightValidation.allowAlert) {
								        ElMessage({
								          type: 'warning',
								          message: `历史数据${weightValidation.message}`,
								          duration: 3000
								        });
								      }
								    }
								  }, 100);
								}
							} else if (historyData.weightStatus === 2) {
								// 二次过磅完成状态
								targetForm.aWeight = historyData.aWeight || 0;
								targetForm.secondWeight = historyData.secondWeight || 0;
								// 保存原始重量
								targetForm.originalAWeight = historyData.aWeight || 0;
								targetForm.originalSecondWeight = historyData.secondWeight || 0;
								targetForm.weightStatus = historyData.weightStatus;
								targetForm.frontendWeighStatus = historyData.weightStatus;
								targetForm.realtimeTarget = 'none';
								targetForm.hasLoadedHistory = true;

								

								// 延迟执行扣重计算，确保所有数据已加载
								// setTimeout(() => {
								// 	// 验证重量逻辑合理性
								// 	const weightValidation = validateWeightLogic(targetForm, loadCode)
								// 	if (weightValidation.valid) {
								// 		// 重量逻辑合理，执行扣重计算
								// 		const result = calculateWeightWithRules(targetForm, loadCode)
								// 		if (result.success) {
											
								// 		}
								// 	} else {
								// 		// 重量逻辑不合理，仅提示用户，不阻止数据加载
										
								// 		ElMessage({
								// 			type: 'warning',
								// 			message: `历史数据${weightValidation.message}`,
								// 			duration: 3000
								// 		})
								// 	}
								// }, 100)
								
								setTimeout(() => {
								  const weightValidation = validateWeightLogic(targetForm, loadCode);
								  if (weightValidation.valid) {
								    const result = calculateWeightWithRules(targetForm, loadCode);
								    if (result.success) {}
								  } else {
								    // 新增：仅 allowAlert 为 true 时才弹框
								    if (weightValidation.allowAlert) {
								      ElMessage({
								        type: 'warning',
								        message: `历史数据${weightValidation.message}`,
								        duration: 3000
								      });
								    }
								  }
								}, 100);










							}

							targetForm.weightsAdjusted = true;
						} else {
							// 无历史数据时初始化表单

							targetForm.id = null;
							targetForm.cargoName = ''; // 货物名称
							targetForm.driverName = ''; // 司机姓名
							targetForm.containerNum='';
							targetForm.shippingCompanyId = ''; // 发货厂家
							targetForm.receivingCompanyId = ''; // 收货厂家
							targetForm.specifications = ''; // 规格
							targetForm.aWeight = 0; // 一次过磅重量
							targetForm.secondWeight = 0; // 二次过磅重量
							targetForm.suttle = 0; // 净重
							targetForm.weightStatus = 0; // 过磅状态（后端字段）
							targetForm.frontendWeighStatus = 0; // 过磅状态（前端状态）
							targetForm.deductingId = ''; // 扣重ID
							targetForm.weighingType = 1; // 默认过磅类型（采购）

							// 2. 重置辅助状态字段
							targetForm.historicalAWeight = 0; // 历史一次重量
							targetForm.historicalSecondWeight = 0; // 历史二次重量
							targetForm.weightsAdjusted = false; // 重量是否已调整
							targetForm.realtimeTarget = 'aWeight'; // 实时数据目标字段
							targetForm.hasLoadedHistory = false; // 是否加载过历史数据
							targetForm.isManualAdjust = false; // 是否手动调整
							targetForm.isLoadingHistory = false; // 是否正在加载历史数据
							saveFormCache(loadCode, targetForm);
						}

						// 更新缓存
						localStorage.setItem(CACHE_CONFIG.getKey(loadCode), JSON.stringify({
							data: { ...targetForm },
							timestamp: Date.now()
						}));
					} else {
						// 请求失败但仍需保留车牌号（优化错误提示内容）
						const errMsg = res.data.message || `查询${upperCardCode}暂无过磅计划`;

						targetForm.autoLicense = upperCardCode;

						// 初始化表单为新车辆状态
						targetForm.id = null;
						targetForm.cargoName = ''; // 货物名称
						targetForm.driverName = ''; // 司机姓名
						targetForm.containerNum='';
						targetForm.shippingCompanyId = ''; // 发货厂家
						targetForm.receivingCompanyId = ''; // 收货厂家
						targetForm.specifications = ''; // 规格
						targetForm.aWeight = 0; // 一次过磅重量
						targetForm.secondWeight = 0; // 二次过磅重量
						targetForm.suttle = 0; // 净重
						targetForm.weightStatus = 0; // 过磅状态（后端字段）
						targetForm.frontendWeighStatus = 0; // 过磅状态（前端状态）
						targetForm.deductingId = ''; // 扣重ID
						targetForm.weighingType = 1; // 默认过磅类型（采购）

						// 2. 重置辅助状态字段
						targetForm.historicalAWeight = 0; // 历史一次重量
						targetForm.historicalSecondWeight = 0; // 历史二次重量
						targetForm.weightsAdjusted = false; // 重量是否已调整
						targetForm.realtimeTarget = 'aWeight'; // 实时数据目标字段
						targetForm.hasLoadedHistory = false; // 是否加载过历史数据
						targetForm.isManualAdjust = false; // 是否手动调整
						targetForm.isLoadingHistory = false; // 是否正在加载历史数据

						saveFormCache(loadCode, targetForm);
						// 非500错误用info，避免用户恐慌
						ElMessage({
							type: res.data.code >= 500 ? 'error' : 'info',
							message: errMsg,
							duration: 2000
						});
					}
				} catch (error : any) {
					requestPromise.isRejected = true;
					// 捕获网络错误或接口异常（优化错误提示）
					const errMsg = error?.data?.message || error?.message || '网络请求异常，请检查网络';
					

					// 重置表单状态
					targetForm.id = null;
					targetForm.cargoName = ''; // 货物名称
					targetForm.driverName = ''; // 司机姓名
					targetForm.containerNum='';
					targetForm.shippingCompanyId = ''; // 发货厂家
					targetForm.receivingCompanyId = ''; // 收货厂家
					targetForm.specifications = ''; // 规格
					targetForm.aWeight = 0; // 一次过磅重量
					targetForm.secondWeight = 0; // 二次过磅重量
					targetForm.suttle = 0; // 净重
					targetForm.weightStatus = 0; // 过磅状态（后端字段）
					targetForm.frontendWeighStatus = 0; // 过磅状态（前端状态）
					targetForm.deductingId = ''; // 扣重ID
					targetForm.weighingType = 1; // 默认过磅类型（采购）

					// 2. 重置辅助状态字段
					targetForm.historicalAWeight = 0; // 历史一次重量
					targetForm.historicalSecondWeight = 0; // 历史二次重量
					targetForm.weightsAdjusted = false; // 重量是否已调整
					targetForm.realtimeTarget = 'aWeight'; // 实时数据目标字段
					targetForm.hasLoadedHistory = false; // 是否加载过历史数据
					targetForm.isManualAdjust = false; // 是否手动调整
					targetForm.isLoadingHistory = false; // 是否正在加载历史数据

					saveFormCache(loadCode, targetForm);
					// 网络错误提示增加操作建议
					ElMessage({
						type: 'error',
						message: `查询失败：${errMsg}`,
						duration: 2500
					});
					
					throw error
				} finally {
					 await nextTick();
					 
					// 无论成功失败，都需要清理状态
					targetForm.isLoadingHistory = false;
					disableRealtimeUpdate.value[loadCode] = { status: false, reason: '' };
			
				}
			})();

			// 将请求加入请求池
			pendingHistoryRequests.set(requestKey, requestPromise);
			// 返回请求Promise，允许外部await
			return requestPromise;
		} catch (error : any) {
			// 捕获函数外层异常（如参数错误）
			const errMsg = error?.message || '查询历史数据时发生错误';
		
			targetForm.isLoadingHistory = false;
			disableRealtimeUpdate.value[loadCode] = { status: false, reason: '' };
			ElMessage({
				type: 'error',
				message: `流程错误：${errMsg}`,
				duration: 2500
			});
		} finally {
			// 确保请求完成后从请求池移除（防止内存泄漏）
			const upperCardCode = cardCode.toUpperCase().trim();
			const requestKey = `${loadCode}_${upperCardCode}`;
			// 延迟移除，确保复用请求完成（关键修复：避免请求未完成就移除）
			setTimeout(() => {
				pendingHistoryRequests.delete(requestKey);
			}, 300);
		}
	};

	// 获取货物列表
	const getCargoNameList = async () => {
		try {
			const res = await proxy.$request.getCargoNameList()
			cargoOptions.value = []
			if (res?.data?.code === 200 && res.data.result) {
				cargoOptions.value = res.data.result
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	// 简化的 handleCompanyChange 方法 - 在状态1或2时触发手动计算
	const handleCompanyChange = (
		type : 'shipping' | 'receiving',
		selectedId : string,
		formData : WeighingFormData,
		loadCode : string
	) => {
		// 在一次过磅完成（状态1）且有二次重量，或二次过磅完成（状态2）时触发扣重计算
		if ((formData.weightStatus === 1 || formData.weightStatus === 2) &&
			formData.aWeight > 0 && formData.secondWeight > 0) {
			// 立即计算扣重（不需要稳定性判断，因为是手动选择厂家触发）
			const result = calculateWeightWithRules(formData, loadCode)
			
		}
	}
	// 获取厂家列表
	const getCompanyNameList = async (num) => {
		try {
			const res = await proxy.$request.getCompanySelect({ companyType: num })
			if (res?.data?.code === 200 && res.data.result) {


				if (num === 1) {
					caiOptions.value = res.data.result
				}
				if (num === 2) {
					xiaoOptions.value = res.data.result
				}
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}

	// 防抖函数
	function debounceFunc(func, wait) {
		let timeout;
		return function executedFunction(...args) {
			const later = () => {
				clearTimeout(timeout);
				func(...args);
			};
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
		};
	}

	// 处理车牌输入

	// 处理车牌输入 - 使用lodash的debounce确保防抖生效
	const handleInput = debounce(function (loadCode, value) {
		const trimmedValue = value.trim();
		const targetForm = loadCode === '1001' ? formAData : formBData;

		// 核心1：车牌号为空 → 重置表单+清除缓存（立即执行，不等待防抖）
		if (!trimmedValue) {
			resetPoundForm(loadCode);
			return;
		}

		const upperValue = trimmedValue.toUpperCase();
		// 核心2：提前赋值车牌，避免防抖期间用户误以为输入未生效
		targetForm.autoLicense = upperValue;
		// 核心3：防抖期间清除旧缓存，避免残留旧数据
		localStorage.removeItem(CACHE_CONFIG.getKey(loadCode));

		// 短于3个字符不触发查询（配合checkLicensePlate的提示）
		if (upperValue.length < 3) {

			return;
		}

		// 仅当车牌长度≥3时，才触发历史查询（防抖生效）
		checkLicensePlate(loadCode, upperValue, true);
	}, 2000, {
		leading: false, // 禁用前缘触发（避免刚输入就触发）
		trailing: true, // 启用后缘触发（输入停止2秒后触发）
		maxWait: 5000 // 最大等待5秒，避免一直不触发（兜底机制）
	});

	// 检查车牌历史数据
	interface WeighingHistory {
		id : number;
		autoLicense : string;
		cargoName : string;
		driverName : string;
		shippingCompanyId : string;
		receivingCompanyId : string;
		specifications : string;
		aWeight : number;
		secondWeight : number;
		suttle : number;
		weightStatus : number;
		deductingId : string;
		weighingType : number;
	}





	const adjustWeightsForWeighingType = async (formData : WeighingFormData, loadCode : string) => {
		if (formData.weightStatus === 0) {
			return;
		}

		// 1. 基础校验：确保有重量可调整
		if (formData.aWeight <= 0 && formData.secondWeight <= 0) {
			ElMessage.warning(`[${loadCode}磅] 无有效重量（一次：${formData.aWeight}t，二次：${formData.secondWeight}t），无法调整`);
			return;
		}

		// 2. 保存原始重量（用于对比是否需要交换）
		const originalA = formData.aWeight;
		const originalB = formData.secondWeight;
		let newA = originalA;
		let newB = originalB;

		// 3. 手动调整核心逻辑（严格按类型交换，不掺杂自动逻辑）
		if (formData.weighingType === 1) { // 采购：必须满足 aWeight（毛重）> secondWeight（皮重）
			if (originalA <= originalB && originalB > 0) { // 只有二次重量存在且大于一次时才交换
				[newA, newB] = [originalB, originalA];
			} else if (originalA <= 0 && originalB > 0) { // 只有二次重量 → 赋值给一次（等待二次）
				newA = originalB;
				newB = 0;
			}
		} else if (formData.weighingType === 2) { // 销售：必须满足 aWeight（皮重）< secondWeight（毛重）
			if (originalA >= originalB && originalB > 0) { // 二次重量存在且小于一次时交换
				[newA, newB] = [originalB, originalA];
			} else if (originalA <= 0 && originalB > 0) { // 只有二次重量 → 赋值给一次（等待二次）
				newA = originalB;
				newB = 0;
			}
		}

		// 4. 应用调整结果（必须更新表单）
		formData.aWeight = newA;
		formData.secondWeight = newB;
		formData.suttle = Math.abs(newA - newB); // 重新计算净重
		await nextTick(); // 确保DOM同步更新

		// 5. 反馈结果
		if (newA !== originalA || newB !== originalB) {
			ElMessage.success(`[${loadCode}磅] 重量手动调整成功：一次=${newA}t，二次=${newB}t`);
		} else {
			// ElMessage.info(`[${loadCode}磅] 重量已符合当前类型规则（无需调整）`);
		}
	};
	// 监听磅单数据变化（放在表单数据定义之后）
	watch(
		() => formAData,
		(newFormData) => {
			if (newFormData.autoLicense || newFormData.cargoName || newFormData.aWeight > 0) {
			
				const cacheKey = CACHE_CONFIG.getKey('1001');
				const cacheData = {
					data: { ...newFormData },
					timestamp: Date.now(),
				};
				localStorage.setItem(cacheKey, JSON.stringify(cacheData));
			}
		},
		{ deep: true, immediate: false }
	);

	watch(
		() => formBData,
		(newFormData) => {
			if (newFormData.autoLicense || newFormData.cargoName || newFormData.aWeight > 0) {
				const cacheKey = CACHE_CONFIG.getKey('1002');
				const cacheData = {
					data: { ...newFormData },
					timestamp: Date.now(),
				};
				localStorage.setItem(cacheKey, JSON.stringify(cacheData));
			}
		},
		{ deep: true, immediate: false }
	);
	watch(
		() => formAData.weighingType,
		(newVal, oldVal) => {
			// 禁用自动调整重量，只记录日志
			if (newVal === oldVal || oldVal === undefined || formAData.isManualAdjust) {
				return;
			}
			
			// 注释掉自动调整：
			// adjustWeightsForWeighingType(formAData, '1001');

			calculateWeightWithRules(formAData, '1001')
			// 同步缓存
			nextTick(() => {
				localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({
					data: { ...formAData },
					timestamp: Date.now()
				}));
			});
		}
	);

	// B磅weighingType监听（修改后）
	watch(
		() => formBData.weighingType,
		(newVal, oldVal) => {
			// 禁用自动调整重量，只记录日志
			if (newVal === oldVal || oldVal === undefined || formBData.isManualAdjust) {
				return;
			}
			
			// 注释掉自动调整：
			// adjustWeightsForWeighingType(formBData, '1002');
			calculateWeightWithRules(formBData, '1002')
			nextTick(() => {
				localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({
					data: { ...formBData },
					timestamp: Date.now()
				}));
			});
		}
	);

	// 过磅状态变化监听（放在表单数据定义之后）
	watch(
		() => formAData.weightStatus,
		(newStatus) => {

			if (newStatus === 0) {
				formAData.realtimeTarget = 'aWeight';
			} else if (newStatus === 1) {
				formAData.realtimeTarget = 'secondWeight';
			} else if (newStatus === 2) {
				// 保持当前target，允许重新开始新一轮称重

			}
			localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({
				data: { ...formAData },
				timestamp: Date.now()
			}));
		}
	);

	watch(
		() => formBData.weightStatus,
		(newStatus) => {

			if (newStatus === 0) {
				formBData.realtimeTarget = 'aWeight';
			} else if (newStatus === 1) {
				formBData.realtimeTarget = 'secondWeight';
			} else if (newStatus === 2) {
				// 保持当前target，允许重新开始新一轮称重

			}
			localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({
				data: { ...formBData },
				timestamp: Date.now()
			}));
		}
	);


	const resetPoundForm = (loadCode : string) => {
	  const targetForm : WeighingFormData = loadCode === '1001' ? formAData : formBData;
	  
	  // 👉 新增核心：同步清空Vuex的3个残留状态（关键！）
	    const oldLicense = counterStore.persistedData.licensePlates[loadCode]; // 获取旧车牌
	  	
	    counterStore.clearPoundData(loadCode); // 1. 清空实时车牌+持久化车牌（调用Vuex现成方法）
	    if (oldLicense) {
	      counterStore.clearLicenseWeighData(loadCode, oldLicense); // 2. 清空该车牌的完整过磅数据
	    }
	
	  // 🔥 关键：彻底清空所有字段（包括触发缓存的aWeight、cargoName等）
	  Object.assign(targetForm, {
	    // 核心字段
	    autoLicense: '',
	    containerNum: '',
	    cargoName: '',
	    driverName: '',
	    shippingCompanyId: '',
	    receivingCompanyId: '',
	    specifications: '',
	    // 重量字段（必须清零，避免aWeight>0触发缓存）
	    aWeight: 0,
	    secondWeight: 0,
	    suttle: 0,
	    originalAWeight: undefined,
	    originalSecondWeight: undefined,
	    // 状态字段
	    id: null,
	    weightStatus: 0,
	    frontendWeighStatus: 0,
	    deductingId: '',
	    weighingType: 1,
	    historicalAWeight: 0,
	    historicalSecondWeight: 0,
	    weightsAdjusted: false,
	    realtimeTarget: 'aWeight',
	    hasLoadedHistory: false,
	    isManualAdjust: false,
	    isLoadingHistory: false,
	    hasSubmittedFirstWeigh: false,
	    lastSecondWeight: 0,
	    secondWeightTimer: null
	  });
	  
	  
	
	  // 🔥 先清除缓存，再阻断后续300ms的缓存写入（避免异步覆盖）
	  const cacheKey = CACHE_CONFIG.getKey(loadCode);
	  localStorage.removeItem(cacheKey);
	  let preventCache = true;
	  setTimeout(() => {
	    preventCache = false;
	  }, 300);
	};



	const handleWeighingTypeChange = async (loadCode : string, newType : number) => {
		const targetForm : WeighingFormData = loadCode === '1001' ? formAData : formBData;
		const oldType = Number(targetForm.weighingType);
		newType = Number(newType);

		// 仅处理有效切换（1=采购，2=销售）
		// if (oldType === newType || !([1, 2].includes(newType))) {
		//   ElMessage.info('无需切换：当前已是选中的过磅类型');
		//   return;
		// }

		if (targetForm.weightStatus === 0) {
			ElMessage.info('无需切换重量!');
			return;
		}

		// / 1. 手动调整前，先阻断实时数据更新（防止干扰）
		disableRealtimeUpdate.value[loadCode] = { status: true, reason: 'manual-type-switch' };
		targetForm.isManualAdjust = true;

		try {
			// 2. 更新过磅类型（关键：先同步表单类型）
			targetForm.weighingType = newType;
			await nextTick(); // 确保DOM和表单状态同步
			

			// 3. 核心：手动调整重量（分两种场景，都要触发）
			if (targetForm.historicalAWeight > 0) {
				// 场景1：有历史数据 → 用历史数据+当前实时重量调整
		
				const currentRealtimeWeight = loadCode === '1001'
					? counterStore.eastPound.weight || 0
					: counterStore.westPound.weight || 0;

				// 按新类型分配重量（采购：a>b；销售：a<b）
				if (newType === 1) { // 采购：毛重（大）→ aWeight，皮重（小）→ secondWeight
					if (targetForm.historicalAWeight > currentRealtimeWeight && currentRealtimeWeight > 0) {
						targetForm.aWeight = targetForm.historicalAWeight;
						targetForm.secondWeight = currentRealtimeWeight;
					} else if (currentRealtimeWeight > 0) {
						targetForm.aWeight = currentRealtimeWeight;
						targetForm.secondWeight = targetForm.historicalAWeight;
					} else {
						// 只有历史数据，无实时数据 → 只赋值aWeight（等待二次过磅）
						targetForm.aWeight = targetForm.historicalAWeight;
						targetForm.secondWeight = 0;
					}
				} else if (newType === 2) { // 销售：皮重（小）→ aWeight，毛重（大）→ secondWeight
					if (targetForm.historicalAWeight < currentRealtimeWeight && currentRealtimeWeight > 0) {
					
						targetForm.aWeight = targetForm.historicalAWeight;
						targetForm.secondWeight = currentRealtimeWeight;
					} else if (currentRealtimeWeight > 0) {
				
						targetForm.aWeight = currentRealtimeWeight;
						targetForm.secondWeight = targetForm.historicalAWeight;
					} else {
				
						targetForm.aWeight = targetForm.historicalAWeight;
						targetForm.secondWeight = 0;
					}
				}
			} else {
				// 场景2：无历史数据 → 直接调用调整函数（核心：必须保留这行！）
			
				await adjustWeightsForWeighingType(targetForm, loadCode);
			}

			// 4. 同步状态和净重（手动调整后必须更新）
			if (targetForm.aWeight > 0 && targetForm.secondWeight > 0) {
				targetForm.frontendWeighStatus = 2; // 二次完成
				targetForm.realtimeTarget = 'none'; // 暂不接收实时数据
			} else if (targetForm.aWeight > 0) {
				targetForm.frontendWeighStatus = 1; // 一次完成
				targetForm.realtimeTarget = 'secondWeight'; // 等待二次过磅
			}
			
	
			// targetForm.suttle = Math.abs(targetForm.aWeight - targetForm.secondWeight); // 重新计算净重
			 calculateWeightWithRules(loadCode === '1001' ? formAData : formBData, loadCode)
			
			
			

			// 5. 保存手动调整结果到缓存
			localStorage.setItem(CACHE_CONFIG.getKey(loadCode), JSON.stringify({
				data: { ...targetForm },
				timestamp: Date.now()
			}));

			// 提示成功
			ElMessage.success(`[${loadCode === '1001' ? '一磅' : '二磅'}] 过磅类型切换成功（手动调整）`);

		} catch (error) {
			console.error(`[${loadCode}] 手动切换过磅类型失败：`, error);
			ElMessage.error('手动切换过磅类型失败，请重试');
		} finally {
			// 6. 关键：必须恢复实时数据更新（之前可能忘记打开导致后续操作失效）
			setTimeout(() => {
				targetForm.isManualAdjust = false;
				disableRealtimeUpdate.value[loadCode] = { status: false, reason: '' }; // 解除禁用
				targetForm.hasLoadedHistory = true; // 标记有历史数据，避免自动逻辑干扰
		
			}, 300); // 延迟确保状态稳定
		}
	};


	// 处理表单提交
	const handleFormAction = async (
		formRef : FormInstance | undefined,
		formData : WeighingFormData,
		action : 'SUBMIT' | 'RESET',
		code : String
	) => {

		if (!formRef) return

		if (action === 'SUBMIT') {
			try {
				await formRef.validate()
				setWeighFeed(formRef, formData, code)
			} catch (e) {
				ElMessage.error('表单验证失败')
			}
		}
	}

	// 提交过磅数据
	const setWeighFeed = async (formRef, formData, num) => {
		try {
			// 验证提交数据的完整性（不修改weightStatus，只做验证）
			if (formData.aWeight === 0 && formData.secondWeight === 0) {
				ElMessage.error('请完成称重后再提交!');
				return;
			}

			if (formData.aWeight === 0) {
				ElMessage.error('一次过磅重量不能为0！');
				return;
			}

			// 确定当前实际提交状态（用于界面逻辑判断，不修改weightStatus）
			const currentSubmitStatus = formData.aWeight > 0 && formData.secondWeight > 0 ? 2 : 1;

			const matchingCargo = cargoOptions.value.find(
				(cargo) => cargo.cargoName === formData.cargoName
			);

			const deductingId = matchingCargo?.id === matchingCargo?.cargoName ? 0 : matchingCargo?.id;

	
				
				
			const originalA = formData.originalAWeight;
			const originalB = formData.originalSecondWeight;
			
			// 定义要传入的aWeight和secondWeight变量
			let aWeight, secondWeight;
			
			
			if(formData.weightStatus===0){
				aWeight=formData.aWeight
				 secondWeight=formData.secondWeight
			}else{
				// 根据weighingType的值计算参数
				if (formData.weighingType === 1) {
				  // 当weighingType为1时：
				  // aWeight取较大值（originalA > originalB则用originalA，否则用originalB）
				  // secondWeight取较小值（与aWeight相反）
				  aWeight = originalA > originalB ? originalA : originalB;
				  secondWeight = originalA > originalB ? originalB : originalA;
				} else if (formData.weighingType === 2) {
				  // 当weighingType为2时：
				  // aWeight取较小值（originalA > originalB则用originalB，否则用originalA）
				  // secondWeight取较大值（与aWeight相反）
				  aWeight = originalA > originalB ? originalB : originalA;
				  secondWeight = originalA > originalB ? originalA : originalB;
				}	
			}
			
			
				
			const res = await proxy.$request.setWeighFeed({
				autoLicense: formData.autoLicense,
				cargoName: formData.cargoName,
				containerNum:formData.containerNum,
				shippingCompanyId: formData.shippingCompanyId,
				receivingCompanyId: formData.receivingCompanyId,
				weightStatus: formData.weightStatus,
				secondWeight: secondWeight,
			
				aWeight:aWeight,
			
				specifications: formData.specifications,
				driverName: formData.driverName,
				id: formData.id,
				deductingId: deductingId,
				weighingType: formData.weighingType
			})


			if (res?.data?.code === 200) {
				// 先保存车牌号用于清理历史缓存
				const currentLicense = formData.autoLicense;

				// 一次过磅和二次过磅提交成功后都清空表单
				formRef.resetFields()

				Object.assign(formData, {
					id: '',
					autoLicense: '',
					cargoName: '',
					containerNum:'',
					shippingCompanyId: '',
					receivingCompanyId: '',
					weightStatus: 0, // 提交完成后重置为0，准备接收新车辆
					secondWeight: 0,
					aWeight: 0,
					specifications: '',
					driverName: '',
					suttle: 0,
					weighingType: 1,
					isManualAdjust: false,
					historicalAWeight: 0,
					hasSubmittedFirstWeigh: false,
					frontendWeighStatus: 0,
					realtimeTarget: 'aWeight',
				})

				// 提交成功后删除缓存
				localStorage.removeItem(CACHE_CONFIG.getKey(num))
				localStorage.removeItem(num)
				counterStore.persistedData.licensePlates[num] = ''
				const historyKey = `history_${currentLicense}`

				localStorage.removeItem(historyKey)


				// 清空历史数据缓存（使用保存的车牌号）
				// if (currentLicense) {
				// 	console.log('currentLicense',currentLicense)
				// 	const historyKey = `history_${currentLicense}`
				// 	if (localStorage.getItem(historyKey)) {

				// 	}
				// }

				const statusText = currentSubmitStatus === 1 ? '一次过磅' : '二次过磅';
			


				ElMessage.success(res.data.message)
			} else {
				ElMessage.error(res?.data?.message || '请求失败')
			}
		} catch (error : any) {
			console.error('API请求错误:', error)
			ElMessage.error(error.data.message || '网络请求异常')
		}
	}


	// 退出登录
	const goOut = () => {
		ElMessageBox.confirm(
			'您确定要退出登录嘛?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(async () => {
			await logout().then(() => {
				ElMessage({ type: 'success', message: '退出成功!' })
				window.location.reload()
			}).catch(err => {
				console.error('退出错误:', err)
				ElMessage({ type: 'error', message: '退出异常:' + err.message })
			})
		}).catch(() => {
			ElMessage({ type: 'info', message: '已取消退出' })
		})
	}

	// 组件激活时检查（路由切换返回时触发）
	onActivated(() => {


		// 东磅激活检查 - 只有当前表单为空且有新车牌号时才查询
		const eastActiveLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;

		if (eastActiveLicense &&
			eastActiveLicense.trim() &&
			eastActiveLicense !== formAData.autoLicense &&
			(!formAData.autoLicense || formAData.autoLicense.trim() === '')) {
		
			checkLicensePlate('1001', eastActiveLicense);
		}

		// 西磅激活检查 - 只有当前表单为空且有新车牌号时才查询
		const westActiveLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;
		if (westActiveLicense &&
			westActiveLicense.trim() &&
			westActiveLicense !== formBData.autoLicense &&
			(!formBData.autoLicense || formBData.autoLicense.trim() === '')) {
		
			checkLicensePlate('1002', westActiveLicense);
		}
	});

	// 组件挂载时初始化 - 用户返回页面时读取缓存和Vuex数据
	onMounted(async () => {


		// 获取货物/厂家列表
		getCargoNameList();
		await Promise.all([getCompanyNameList(1), getCompanyNameList(2)]);

		// 东磅初始化 - 处理缓存和实时数据
		const eastCache = getCacheData('1001');

		const eastVuexLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;

		if (eastCache) {
			// 恢复缓存数据
			Object.assign(formAData, eastCache);
			formAData.isLoadingHistory = false;
			// 同步weightStatus到frontendWeighStatus
			formAData.frontendWeighStatus = eastCache.weightStatus || 0;
			
		}

		// 检查Vuex中是否有新车牌
		if (eastVuexLicense && eastVuexLicense !== formAData.autoLicense) {
			
			formAData.autoLicense = eastVuexLicense;
			checkLicensePlate('1001', eastVuexLicense);
		}

		// 西磅初始化 - 处理缓存和实时数据
		const westCache = getCacheData('1002');
		const westVuexLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;

		if (westCache) {
			// 恢复缓存数据
			Object.assign(formBData, westCache);
			formBData.isLoadingHistory = false;
			// 同步weightStatus到frontendWeighStatus
			formBData.frontendWeighStatus = westCache.weightStatus || 0;
			
		}

		// 检查Vuex中是否有新车牌
		if (westVuexLicense && westVuexLicense !== formBData.autoLicense) {
			
			formBData.autoLicense = westVuexLicense;
			checkLicensePlate('1002', westVuexLicense);
		}

		// 页面可见性变化监听
		const handleVisibilityChange = () => {
			if (document.visibilityState === 'visible') {
				

				const currentEastLicense = counterStore.persistedData.licensePlates['1001'] || counterStore.eastPound.autoLicense;
				// 只有当前表单为空且有新车牌号时才查询
				if (currentEastLicense &&
					currentEastLicense.trim() &&
					currentEastLicense !== formAData.autoLicense &&
					(!formAData.autoLicense || formAData.autoLicense.trim() === '')) {
					
					checkLicensePlate('1001', currentEastLicense);
				}

				const currentWestLicense = counterStore.persistedData.licensePlates['1002'] || counterStore.westPound.autoLicense;
				// 只有当前表单为空且有新车牌号时才查询
				if (currentWestLicense &&
					currentWestLicense.trim() &&
					currentWestLicense !== formBData.autoLicense &&
					(!formBData.autoLicense || formBData.autoLicense.trim() === '')) {
			
					checkLicensePlate('1002', currentWestLicense);
				}
			}
		};
		document.addEventListener('visibilitychange', handleVisibilityChange);

		// 页面离开缓存
		const handleBeforeUnload = () => {
			// 原bug：两个缓存都存了formBData，修改为分别存A/B磅数据
			localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({ data: { ...formAData }, timestamp: Date.now() }));
			localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({ data: { ...formBData }, timestamp: Date.now() }));
		};
		window.addEventListener('beforeunload', handleBeforeUnload);

		// 组件卸载时清理
		onBeforeUnmount(() => {

			window.removeEventListener('beforeunload', handleBeforeUnload);
			document.removeEventListener('visibilitychange', handleVisibilityChange);
			// 原bug：两个缓存都存了formBData，修改为分别存A/B磅数据
			localStorage.setItem(CACHE_CONFIG.getKey('1001'), JSON.stringify({
				data: { ...formAData }, // 原错误：formBData → 改为formAData
				timestamp: Date.now()
			}));
			localStorage.setItem(CACHE_CONFIG.getKey('1002'), JSON.stringify({
				data: { ...formBData },
				timestamp: Date.now()
			}));
			// 卸载时清空请求池，避免内存泄漏
			formAData.isLoadingHistory = false;
			formBData.isLoadingHistory = false;
			pendingHistoryRequests.clear();
			disableRealtimeUpdate.value['1001'] = { status: false, reason: '' };
			disableRealtimeUpdate.value['1002'] = { status: false, reason: '' };
		});
	});
</script>
<style>
	.custom-input-number {
		font-size: 16px;
	}

	.custom-input-number .el-input__inner {
		font-size: 16px;
		font-weight: 600;
	}
</style>


<style lang="scss" scoped>
	.indexBox {
		padding: 8px;
		box-sizing: border-box;
		position: relative;

		.title {
			text-align: center;
			font-size: 32px;
			font-weight: 550;
			position: relative;
		}

		.poundBox {
			width: 100%;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);

			.poundCard {
				min-height: 580px;

				.leftBox {
					padding-left: 50px;
					box-sizing: border-box;

					&_name {
						font-size: 28px;
						font-weight: 550;
						margin-bottom: 4px;
					}
				}

				.rightBox {
					padding-left: 50px;
					box-sizing: border-box;

					&_name {
						font-size: 28px;
						font-weight: 550;
						margin-bottom: 4px;
					}
				}
			}
		}

		/* 弹窗样式 */
		.print-dialog .el-dialog__header {
			text-align: center;
			padding: 10px;
			border-bottom: 1px solid #e4e7ed;
		}

		.print-dialog .el-dialog__title {
			font-size: 16px;
			font-weight: bold;
		}

		.print-dialog .el-dialog__body {
			padding: 15px;
		}

		.print-dialog .el-dialog__footer {
			padding: 10px 15px;
			border-top: 1px solid #e4e7ed;
		}

		.dialog-footer {
			text-align: right;
		}

		/* 表格样式 */
		.print-table table {
			width: 100%;
			border-collapse: collapse;
			border: 1px solid #000;
		}

		.print-table td {
			border: 1px solid #000;
			padding: 5px;
		}
	}
</style>